import 'dart:convert';

import 'package:deepseek_client/ai/service/chat_service.dart';
import 'package:deepseek_client/dto/OllamaLocalModelDTO.dart';
import 'package:deepseek_client/widget/AutoMarquee.dart';
import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

import '../common/SpConstants.dart';
import '../common/utils/SpUtils.dart';

class ModelSelectPage extends StatefulWidget {
  IChatService? service;
  ModelSelectPage({super.key, required this.service});

  @override
  State<StatefulWidget> createState() => _ModelSelectPageState();
}

class _ModelSelectPageState extends State<ModelSelectPage> {

  final ValueNotifier<List<AiModel>?> _supportModelNotifier = ValueNotifier(null);
  var _currentSelectIndex = 0;

  @override
  void initState() {
    super.initState();
    findLocalModels();
  }

  findLocalModels() async{
    try{
      var res = await widget.service?.findModels();
      List<AiModel> _supportModels = res ?? [];
      var localModel = await SpUtils.getInstance().getString(SpConstants.model);
      if(localModel.isEmpty && _supportModels.isNotEmpty){
        localModel = _supportModels.first.name ?? "";
        _supportModels.first.selected = true;
        _currentSelectIndex = 0;
      }else{
        for (var model in _supportModels) {
          model.selected = model.name == localModel;
          if(model.selected == true){
            _currentSelectIndex = _supportModels.indexOf(model);
          }
        }
      }
      _supportModelNotifier.value = _supportModels;
    }catch (e){
      print(e);
    }
  }


  @override
  Widget build(BuildContext context) {
    var screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Container(
          constraints: BoxConstraints(
            minWidth: 0,
            maxWidth: screenWidth / 2,
            minHeight: 0,
            maxHeight: kToolbarHeight
          ),
          child: const AutoMarquee(
            value: "「炎龙」目前支持下列模型",
            style: TextStyle(
                color: Color(0xFF141414),
                fontSize: 20,
                fontWeight: FontWeight.w600),
          ),
        ),
        elevation: 0.5,
        leading: GestureDetector(
          onTap: () async {
            Navigator.of(context).pop();
          },
          child: const Icon(
            Icons.arrow_back_ios,
            color: Color(0xFF141414),
          ),
        ),
      ),
      body: ValueListenableBuilder(valueListenable: _supportModelNotifier, builder: (context , models , child){
        if(models == null){
          return const Center(
            child: TDLoading(
              size: TDLoadingSize.large,
              icon: TDLoadingIcon.circle,
              axis: Axis.vertical,
              iconColor: Colors.white,
              textColor: Colors.white,
              duration: 700,
            ),
          );
        }
        if(models.isEmpty){
          return const Center(
            child: Text("暂无模型" , style: TextStyle(
              color: Color(0xFF141414),
              fontSize: 16
            ),),
          );
        }
        return ListView.builder(itemBuilder: (context , index){
          return ListTile(
            title: Text(models[index].name ?? "" , style: const TextStyle(
              color: Color(0xFF141414),
              fontSize: 16
            ),),
            trailing: models[index].selected == true ? const Icon(Icons.check , color: Color(0xFF141414),) : null,
            onTap: ()  {
              var lastList = List<AiModel>.from(_supportModelNotifier.value ?? []);
              lastList[_currentSelectIndex].selected = false;
              lastList[index].selected = true;
              _supportModelNotifier.value = lastList;
              _currentSelectIndex = index;
              SpUtils.getInstance().put(SpConstants.model, lastList[index].name ?? "");
            }
           );
        } , itemCount: models.length, shrinkWrap: false,);
      }),
    );
  }
}
